﻿using EntityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers
{
    [Route("yjh/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly HallDbcontext _DB;

        public UserController(HallDbcontext context)
        {
            _DB = context;
        }

        [HttpGet]
        //public List<EM_User> GetAllUser()
        //{
        //    //寻找所有相似的
        //    return _DB.EM_User.ToList();
        //}

        public Result GetAlUser()
        {
            var UserName = _DB.EM_User.Where(w => w.FirstName == "张三").Select(s => new {
                s.FirstName,
                s.LastName
            }).FirstOrDefault();

            Result result = new Result();
            result.Date = UserName;
            result.Code = 200;
            return result;
        }

        [HttpGet("{Id}/{userName}")]
        public Result Get(Guid Id, string userName)
        {
            Result result = new Result();
            // where: 过滤行
            // select: 过滤列
            // tolist(): 筛选一个范围的数据(集合)
            // FirstOrDefault(): 筛选第一条符合条件的数据行(对象)
            // <> : 确认数据类型( 泛型 )

            EM_User? resulrData = _DB.EM_User.Where(w => w.Id == Id).FirstOrDefault<EM_User>();
            if (resulrData == null)
            {
                result.Code = 404;

            }
            else
            {
                result.Code = 200;
                result.Data = resulrData;
            }
            return result;
        }

        [HttpPost]
        public Result AddUser([FromBody] EM_User user)
        {
            Result result = new Result();
            _DB.EM_User.Add(user);
            _DB.SaveChanges();
            return result;
        }

        [HttpDelete]
        public Result DelUser(Guid id)
        {
            Result result = new Result();
            EM_User? user = _DB.EM_User.Where(w => w.Id == id).SingleOrDefault();
            if (user != null)
                _DB.EM_User.Remove(user);
            result.Data = _DB.SaveChanges();
            return result;
        }


        [HttpPut]
        public Result UpUser([FromBody] EM_User user)
        {
            Result result = new Result();
            _DB.EM_User.Update(user);
            result.Date = _DB.SaveChanges();
            return result;
        }
    }
}
